package com.zjut.zs.file.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.SimplifiedObjectMeta;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zjut.an.config.dao.AnConfig;
import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.log.dao.AnLog;
import com.zjut.an.log.manager.AnLogManager;
import com.zjut.an.util.module.PageModule;
import com.zjut.an.util.system.Status;
import com.zjut.an.util.tools.DateUtil;
import com.zjut.an.util.tools.FileDownload;
import com.zjut.an.util.tools.JSONUtilClass;
import com.zjut.an.util.tools.MD5;
import com.zjut.an.util.tools.StringUtil;
import com.zjut.common.idgen.IdGenerate;
import com.zjut.zs.file.dao.ZsFile;
import com.zjut.zs.file.manager.FilePath;
import com.zjut.zs.file.manager.ZsFileManager;
import com.zjut.zs.hjqk.dao.ZsHjqk;
import com.zjut.zs.hjqk.manager.ZsHjqkManager;
import com.zjut.zs.school.dao.ZsSchool;
import com.zjut.zs.school.manager.ZsSchoolManager;
import com.zjut.zs.shhd.dao.ZsShhd;
import com.zjut.zs.shhd.manager.ZsShhdManager;
import com.zjut.zs.user.dao.ZsUser;
import com.zjut.zs.user.manager.ZsUserManager;
import com.zjut.zs.userstatus.dao.ZsUserStatus;
import com.zjut.zs.userstatus.manager.ZsUserStatusManager;
import com.zjut.zs.util.tools.ZsHTMLCreat;
import com.zjut.zs.zxlb.dao.ZsZxlb;
import com.zjut.zs.zxlb.manager.ZsZxlbManager;

//import org.junit.Assert;
import net.sf.json.JSONObject;

public class ZsFileAction extends ActionSupport implements
		ServletResponseAware, ServletRequestAware, ModelDriven<ZsFile> {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;

	private ZsFile obj;
	private Map<String, Object> dataMap;
	private int offset = 0, limit = 10;
	private String order;
	private String sort;
	private String search;
	private String rowstr;
	

	private File[] file; // 上传的文件
	private String[] fileFileName; // 文件名称
	private String[] fileContentType; // 文件类型
	private String idcard;
	private String fileFileNames = ""; // 文件名称

	@Resource(name = "AnConfigManager")
	private AnConfigManager anconfig;

	@Resource(name = "ZsFileManager")
	private ZsFileManager manager;

	@Resource(name = "ZsUserManager")
	private ZsUserManager umanager;

	@Resource(name = "ZsSchoolManager")
	private ZsSchoolManager scmanager;
	
	@Resource(name = "FileDownload")
	private FileDownload filedownload;
	
	@Resource(name = "ZsFileManager")
	private ZsFileManager fmanager;
	
	@Resource(name = "ZsUserStatusManager")
	private ZsUserStatusManager smanager;

	@Resource(name = "AnLogManager")
	private AnLogManager logmanager;
	
	@Resource(name = "ZsHTMLCreat")
	private ZsHTMLCreat html;
	
	@Resource(name = "IdGenerate")
	private IdGenerate idgenerate;
	
	@Resource(name = "StringUtil")
	private StringUtil stringutil;

	@Resource(name = "DateUtil")
	private DateUtil dateutil;
	
	public String zsFileList() {
		try {
			request.setCharacterEncoding("UTF-8");
			dataMap = new HashMap<String, Object>();
			int pageNumber = offset / limit + 1;
			PageModule module = manager.getDataByInstance(pageNumber, limit,
					sort, order, obj);
			dataMap.put("rows", module.getObjects());
			dataMap.put("total", module.getTotal());
			obj = null;
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	@SuppressWarnings("unchecked")
	public String zsFileDeletes() {
		try {
			String objumniJSON = rowstr;
			manager.deleteDatas(JSONUtilClass.getDTOList(objumniJSON,
					ZsFile.class));
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String zsFileAdd() {
		try {
			String objumniJSON = rowstr;
			obj = (ZsFile) JSONUtilClass.getDTO(objumniJSON, ZsFile.class);
			obj.setFiId(idgenerate.nextId());
			//manager.addData(obj);
			System.out.println("############## "+obj.getFiFile());
			String[] Str1Array = obj.getFiFile().split(";");			
			for(int i=0;i<Str1Array.length;i++){
				System.out.println(Str1Array[i]);
				obj.setAddTime(dateutil.getCurrentDate5());
				obj.setFiFile(Str1Array[i]);
				
				SimplifiedObjectMeta objectmeta = filedownload.downloadFile(Str1Array[i], umanager.getData(obj.getZsUser().getUsId()).getUsIdcard());
				obj.setFiCheck(String.valueOf(objectmeta.getSize()));
				manager.addData(obj);
				
				AnLog log = new AnLog(obj.getZsUser().getUsId(), "报考日志",logmanager.subIdcard(((ZsUser)session.getAttribute("zsUser")).getUsIdcard())+"于"+dateutil.getCurrentDate5()+"上传材料<a href='"+manager.getFileURL("是", obj.getFiFile(), ((ZsUser)session.getAttribute("zsUser")).getUsIdcard(), true)+"' target='_blank'>"+obj.getFiName()+"</a>", dateutil.getCurrentDate5());
				logmanager.addData(log);
			}		
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String zsFileDelete() {
		try {
			String objumniJSON = rowstr;
			// manager.deleteData((ZsFile)JSONUtilClass.getDTO(objumniJSON,
			// ZsFile.class));
			String key = request.getParameter("key");
			String usId = manager.getData(request.getParameter("fiId")).getZsUser().getUsId();
			if(MD5.toMD5(String.valueOf(usId)).equals(key)) {
				ZsUser user = umanager.getData(usId);
				obj = manager.getData(request.getParameter("fiId"));
				AnLog log = new AnLog(obj.getZsUser().getUsId(), "报考日志",logmanager.subIdcard(((ZsUser)session.getAttribute("zsUser")).getUsIdcard())+"于"+dateutil.getCurrentDate5()+"删除材料<a href='"+manager.getFileURL("是", obj.getFiFile(), ((ZsUser)session.getAttribute("zsUser")).getUsIdcard(), true)+"' target='_blank'>"+obj.getFiName()+"</a>", dateutil.getCurrentDate5());
				logmanager.addData(log);
				
				manager.deleteData(obj);
				dataMap = new HashMap<String, Object>();
				dataMap.put("flag", "success");
				smanager.updatefileStatus(user);	
				return SUCCESS;
			}else{
				return ERROR;
			}				
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String zsFileUpdate() {
		try {
			String objumniJSON = rowstr;
			obj = (ZsFile) JSONUtilClass.getDTO(objumniJSON,
					ZsFile.class);
			manager.updateData(obj);

			AnLog log = new AnLog(obj.getZsUser().getUsId(), "报考日志",logmanager.subIdcard(((ZsUser)session.getAttribute("zsUser")).getUsIdcard())+"于"+dateutil.getCurrentDate5()+"修改材料<a href='"+manager.getFileURL("是", obj.getFiFile(), ((ZsUser)session.getAttribute("zsUser")).getUsIdcard(), true)+"' target='_blank'>"+obj.getFiName()+"</a>", dateutil.getCurrentDate5());
			logmanager.addData(log);
			
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String zsFileCheck() {
		try {
			String fiId = request.getParameter("fiId");
			obj = manager.getData(fiId);
			if (obj.getFiCheck() == null) {
				obj.setFiCheck(Status.ERROR.getStatus());
				manager.updateData(obj);
			} else {
				obj.setFiCheck(null);
				manager.updateData(obj);
			}
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String zsFileSave() {
		obj = (ZsFile) JSONUtilClass.getDTO(rowstr, ZsFile.class);
		ZsSchool school = new ZsSchool();
		school = (ZsSchool)scmanager.getDataByInstance(1,1,null,null,school).getObjects().get(0);
		if(Status.ON.getStatus().equals(school.getScFilesendActive()) || Status.APPSTATUS_NOTIME.getStatus().equals(smanager.getDataByUser(obj.getZsUser()).getAppStatus())) {//如果仍然可以上传
			if (!stringutil.isEmpty(obj.getFiId())) {
				// -------update-------
				zsFileUpdate();
			} else {
				// -------insert-------
				zsFileAdd();
				ZsUser user = umanager.getData(obj.getZsUser().getUsId());
				smanager.updatefileStatus(user);
			}
		} else {
			return ERROR;
		}
		rowstr = null;
		return SUCCESS;
	}

	public String zsFileSave2() {
		try {
			String objumniJSON = rowstr;
			obj = (ZsFile) JSONUtilClass.getDTO(objumniJSON, ZsFile.class);
			
			if (obj.getFiFile() != null) {
				String[] strarray = obj.getFiFile().split("\\|");
				for (int k = 0; k < strarray.length; k++) {
					obj.setFiFile(strarray[k]);
					manager.addData(obj);
				}
				rowstr = null;
				return SUCCESS;
			}else{
				return ERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}

	}

	public String zsFile() {
		try {
			request.setCharacterEncoding("UTF-8");
			dataMap = new HashMap<String, Object>();
			String fiId = request.getParameter("fiId");
			obj = manager.getData(fiId);
			dataMap.put("rows", obj);
			obj = null;
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}

	public String postObjectPolicy() {
		dataMap = new HashMap<String, Object>();
		
		String host = "http://" + FilePath.bucketName + "." + FilePath.endpoint; // host的格式为 bucketname.endpoint
		if("1".equals(html.getJsonValue("https"))) {
			host = "https://" + FilePath.bucketName + "." + FilePath.endpoint;
		}
		OSSClient client = new OSSClient(FilePath.endpoint, FilePath.accessKeyId, FilePath.accessKeySecret);
		try {
			long expireTime = 120;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, FilePath.dir);

			String postPolicy = client.generatePostPolicy(expiration, policyConds);
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);

			dataMap.put("accessid", FilePath.accessKeyId);
			dataMap.put("policy", encodedPolicy);
			dataMap.put("signature", postSignature);
			dataMap.put("dir", FilePath.dir);
			dataMap.put("host", host);
			dataMap.put("expire", String.valueOf(expireEndTime / 1000));
			

		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			client.shutdown();
		}
		
		return SUCCESS;
	}

	

	@Override
	public ZsFile getModel() {
		if (null == obj) {
			obj = new ZsFile();
		}
		return obj;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public ZsFile getAl() {
		return obj;
	}

	public void setAl(ZsFile obj) {
		this.obj = obj;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getRowstr() {
		return rowstr;
	}

	public void setRowstr(String rowstr) {
		this.rowstr = rowstr;
	}

	public ZsFileManager getManager() {
		return manager;
	}

	public void setManager(ZsFileManager manager) {
		this.manager = manager;
	}

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}

	public String[] getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String[] fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String[] getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String[] fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileNames() {
		return fileFileNames;
	}

	public void setFileFileNames(String fileFileNames) {
		this.fileFileNames = fileFileNames;
	}

	public String getIdcard() {
		return idcard;
	}

	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}



}
